import random
import string
from flask import Blueprint,render_template,request,jsonify,redirect,url_for,session
from exts import mail,db
from flask_mail import Message
from models import EmailCaptchaModel
from forms import  RegisterForm,LoginForm
from models import UserModel,EmailCaptchaModel
from werkzeug.security import generate_password_hash, check_password_hash


Bp = Blueprint("auth",__name__,url_prefix="/auth")

@Bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        email = request.form['email']
        password = request.form['password']
        print('email='+email)
        print('password='+password)


        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在！")
                return redirect(url_for("auth.login"))
            if check_password_hash(user.password, password):
                # cookie：
                # cookie中不适合存储太多的数据，只适合存储少量的数据
                # cookie一般用来存放登录授权的东西
                # flask中的session，是经过加密后存储在cookie中的
                session['user_id'] = user.id
                return redirect(url_for('index'))
            else:
                print("密码错误！")
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))

@Bp.route('/logout')
def logout():
    session.clear()
    # return render_template('index.html')
    return redirect("/")

@Bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:#如果是POST请求
        # 验证用户提交的邮箱和验证码是否对应且正确
        # 表单验证：flask-wtf: wtforms

        #调试用
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        password_confirm = request.form['password_confirm']
        email_captcha = request.form['email_captcha']
        print('email='+email)
        print('email_captcha='+email_captcha)
        print('username='+username)
        print('password='+password)
        print('password_confirm='+password_confirm)



        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("auth.login"))
            # return 'success'
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))


@Bp.route("/history")
def history():
    print("history")
    return render_template("history.html")

@Bp.route("/reporter")
def reporter():
    print("reporter")
    return render_template("reporter.html")

@Bp.route("/warning")
def warning():
    print("warning")
    return render_template("warning.html")


@Bp.route("/equip")
def equip():
    print("equip")
    return render_template("equip.html")

@Bp.route("/user_manage")
def user_manage():
    return render_template("usermanage.html")

#发送邮件测试
#recipients参数：用于存放邮件接收者
@Bp.route("/email/test")
def send_mail():
    message = Message(subject='邮箱测试主题',recipients=['528188956@qq.com'],body= '测试')
    mail.send(message)
    return 'mail send ok'

#发送验证码
@Bp.route('/captcha/email')
def send_mail_captcha():
    #1. 获取用户传入的邮箱
    #/mail/checkcod?email = 1149....
    email = request.args.get("email")
    #2. 4或6位验证码的产生随机的数和字母组合
    source =  string.digits*4
    captcha =random.sample(source,4)
    captcha = "".join(captcha)
    #3.发送邮件
    message = Message(subject='验证码',recipients=[email],body= f'验证码是:{captcha}')
    mail.send(message)
    # 指定时间将数据同步，将验证码存储到缓存中，memcached
    # memcached/redis
    #本项目用数据库存储，数据存在硬盘中，数据交换比较慢
    email_captcha = EmailCaptchaModel(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    # RESTful API
    # {code: 200/400/500, message: "", data: {}}
    return jsonify({"code": 200, "验证码": captcha})

